package finance

import com.gargoylesoftware.htmlunit.WebClient
import com.gargoylesoftware.htmlunit.html.HtmlPage
import org.joda.time.format.*

class NasdaqHistoryService {

    static transactional = true

    def retrieve(symbol) {
        final WebClient webClient = new WebClient()
        webClient.setJavaScriptEnabled(false)
//        HtmlPage page = webClient.getPage("http://www.nasdaq.com/aspx/historical_quotes.aspx?symbol=AAPL&selected=AAPL");
        def instrument = Instrument.findBySymbol(symbol)
        log.info( instrument.symbol )
        requestAndSave(instrument, webClient)
        
        webClient.closeAllWindows();
    }
    
    
    def saveValueByFieldName(fieldName, dateTime, instrument, val) {
        def mnemonic = Field.findByName(fieldName)
        def fVal = new FieldValue(added: dateTime, val: val, instrument: instrument, field:mnemonic).save();
  }
    
    def requestAndSave(instrument, webClient) { 
        def page = webClient.getPage("http://charting.nasdaq.com/ext/charts.dll?2-1-14-0-0-5120-03NA000000" 
                + instrument.symbol 
                + "-&SF:4|5-WD=539-HT=395--XTBL-")
        def trs = page.getByXPath("//table/tbody/tr[2]/td[2]/center/table/tbody/tr")
        
        trs.each { 
            (it.asText() =~ /(\d+\/\d+\/\d+)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)\s+([\d.]+)\s+([\d,]+)/).each {
               all, date, open, high, low, close, volume -> 
               def dateTime = DateTimeFormat.forPattern("MM/dd/yyyy").parseDateTime(date)
               saveValueByFieldName('Open', dateTime, instrument, open)
               saveValueByFieldName('High', dateTime, instrument, high)
               saveValueByFieldName('Low', dateTime, instrument, low)
               saveValueByFieldName('Close', dateTime, instrument, close)
               saveValueByFieldName('Volume', dateTime, instrument, volume.replaceAll(",", ""))
            }
        }
        
        page.cleanUp()
    }
}
